package com.cqgcxy.shopping.controller;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqgcxy.shopping.common.CommException;
import com.cqgcxy.shopping.domain.User;
import com.cqgcxy.shopping.service.UserService;




@WebServlet(urlPatterns="/user/login.do")
public class LoginServlet extends HttpServlet{

	private static final long serialVersionUID = -6204376603444672194L;
	private Logger  logger = LoggerFactory.getLogger(getClass());
	private UserService userService=new UserService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		logger.info("1111");
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("login.dopost");
		try {
			// 1.抽取参数，封装为实体对象
			String usercode=req.getParameter("usercode");
			String password=req.getParameter("password");
			logger.debug("获取参数成功：{},{},{}",usercode,password);
			// 2.类型转换
			logger.debug("类型转换成功");
			// 3.数据校验
			//账号不为空
			if(usercode==null||usercode.trim().length()<=0) {
				throw new CommException("账号不能为空");
			}
			//密码不能为空
			if(password==null||password.trim().length()<6) {
				throw new CommException("密码长度错误");
			}
		/*	if(kaptcha==null||kaptcha.trim().length()<0) {
				throw new CommException("验证码错误");
			}
			
			Object object=session.getAttribute("kaptcha"); //获取session中的验证码
			if(!kaptcha.equals(object)) {
				throw new CommException("验证码输入错误");
			}*/
			logger.debug("校验成功");
			//4.参数封装为对象
			User user = new User();
			user.setUsercode(usercode);
			user.setPassword(password);
			
			// 5.调用业务方法
			
			HttpSession session=req.getSession();
			session.setAttribute("user", user);
			logger.debug("业务处理成功");
			userService.login(usercode, password);
			// 6.转发或者重定向
			resp.sendRedirect(req.getContextPath()+"/index.jsp");//重定向
			logger.debug("登陆成功");
			
		} catch (Exception e) {
			req.setAttribute("error", e.getMessage());
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
			logger.info("登录失败:{}",e.getMessage());
		}
		
	}
}
